package com.lqk.filelock;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FileLockDemo1 {
    public static void main(String[] args) throws Exception {
        String input="lqk";
        System.out.println("input："+input);

        ByteBuffer buffer = ByteBuffer.wrap(input.getBytes());

        String filePath="f:\\lqk\\01.txt";

        Path path = Paths.get(filePath);

        FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.WRITE,StandardOpenOption.APPEND);

        fileChannel.position(fileChannel.size()-1);

        // 加锁
        FileLock lock = fileChannel.lock(0L,Long.MAX_VALUE,true);
        System.out.println("是否是共享锁："+lock.isShared());

        fileChannel.write(buffer);
        fileChannel.close();

        // 读文件
        readFile(filePath);

    }

    private static void readFile(String filePath) throws Exception {
        FileReader fileReader=new FileReader(filePath);
        BufferedReader bufferedReader=new BufferedReader(fileReader);

        String str = bufferedReader.readLine();
        System.out.println("读取出的内容："+str);

        while (str !=null){
            System.out.println("---->"+str);
            str = bufferedReader.readLine();
        }
        fileReader.close();
        bufferedReader.close();
    }
}
